<template>
  <Page :title='dictName' @gesture='onGesture' :on-page-back='onPageBack'>
    <template #content>
      <div class='w-full h-full p-20px box-border'>
        <div class='dictIndex box-border flex flex-col'>
          <div>
            <el-input
              clearable
              class='input-search'
              placeholder='智能查词'
              v-model='searchValue'
              @input='onSearchInput'>
              <i slot='prefix' class='el-input__icon el-icon-search'></i>
            </el-input>
          </div>
          <div v-show="searchValue===''">
            <div class='title'>历史</div>
            <div class='list'>
              <div class='word-item' v-for='(item,index) in historyList' :key='index'
                   @click='onHistoryClick(item)'>
                {{ item }}
              </div>
              <div class='word-item__more' v-if='showHistoryLength < history.length' @click="showMore('history')">
                <span>查看更多</span>
                <i class='word-item-icon el-icon-arrow-down' />
              </div>
            </div>
          </div>
          <div v-show="currentWord!==''" class='list'>
            <div class='word-item' @click='onWordClick(currentWord)'>
              {{ currentWord }}
            </div>
          </div>
          <div v-show="searchValue!==''">
            <div class='title'>形近词目</div>
            <div class='list'>
              <div class='word-item' v-for='(item,index) in wordList' :key='index'
                   @click='onWordClick(item)'>
                {{ item }}
              </div>
              <div class='word-item__more' v-if='showWordLength < words.length' @click="showMore('words')">
                <span>查看更多</span>
                <i class='word-item-icon el-icon-arrow-down' />
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </Page>
</template>
<script>
import { debounce } from '@/utils'
import Page from '@/components/page'
import { MODULE_ID } from '@/store/modules/module-use'

export const dictMap = {
  1: '英汉双解词典',
  2: '汉英综合词典',
  3: '现代汉语词典',
  4: '古汉语词典',
  5: '日语词典'
}
export const dictUrlMap = {
  1: 'yhmdx.db',
  2: 'hymdx.db',
  3: 'xdhymdx.db',
  4: 'gdhymdx.db',
  5: 'jpmdx.db'
}
export default {
  components: { Page },
  data() {
    return {
      dictId: '',
      searchValue: '',
      history: [],
      words: [],
      showHistoryLength: 15,
      showWordLength: 15,
      currentWord: ''
    }
  },
  computed: {
    historyList() {
      return this.history.slice(0, this.showHistoryLength)
    },
    wordList() {
      return this.words.slice(0, this.showWordLength)
    },
    dictName() {
      if (!this.dictId) return ''
      return dictMap[this.dictId]
    }
  },
  methods: {
    init() {
      this.$store.dispatch('resetMyDict')
      let dictId = JSON.parse(this.$route.query.id)
      if (dictId) {
        this.dictId = dictId
      }
      const loading = this.$loading({
        target: '.dictIndex',
        body: false,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      try {
        const dictFileName = this.dictId ? dictUrlMap[this.dictId] : dictUrlMap[1]
        const callback = (result) => {
          console.log('定时回调', result)
          if (result == 1) {
            clearInterval(cyclicEvent)
            loading.close()
          }
        }
        const callBackName = `fn${new Date().getTime()}`
        window.android_call[callBackName] = callback.bind(this)
        let cyclicEvent = setInterval(() => {
          android.fileIsExist(dictFileName, callBackName)
        }, 1000)
      } catch (e) {
        this.$message.error('加载文件失败')
        loading.close()
      }
    },
    resetData() {
      this.currentWord = ''
      this.searchValue = ''
      this.words = []
      this.showHistoryLength = 15
    },
    showMore(type) {
      if (type === 'history') {
        this.showHistoryLength += 15
      } else {
        this.showWordLength += 15
      }
    },
    onSearchInput() {
      debounce(() => {
        this.getWordList()
      }, 1000)()
    },
    async getWordList() {
      const that = this
      let word = this.searchValue
      try {
        const callback = (result) => {
          let list = JSON.parse(result)
          if (list && list.length !== 0) {
            const isHaveCurrent = list.some((item, index) =>{
              if(item === word.toLowerCase()){
                console.log(item,word)
                list.splice(index, 1)
                return true
              }
            })
            console.log(isHaveCurrent)
            if (isHaveCurrent) {
              that.currentWord = word
            } else {
              that.currentWord = ''
            }
            console.log(that.currentWord)
          }
          that.words = list
        }
        const callBackName = `fn${new Date().getTime()}`
        window.android_call[callBackName] = callback.bind(this)

        switch (this.dictId) {
          case 1:
            android.yhsearchLike(word, callBackName)
            break
          case 2:
            android.hysearchLike(word, callBackName)
            break
          case 3:
            android.xdhysearchLike(word, callBackName)
            break
          case 4:
            android.gdhysearchLike(word, callBackName)
            break
          case 5:
            android.jpsearchLike(word, callBackName)
            break
        }
      } catch (e) {
        console.log(e)
        this.$message.error(`搜索失败.`)
      }
    },
    getHistoryList() {
      // 获取历史记录
      let historyJson = localStorage.getItem('dictHistory' + this.dictId)
      if (historyJson) {
        this.history = JSON.parse(historyJson)
      }
    },
    addHistory(word) {
      // 添加历史记录
      this.history.unshift(word)
      let historyJson = JSON.stringify(this.history)
      localStorage.setItem('dictHistory' + this.dictId, historyJson)
    },
    onPageBack() {
      this.$router.back()
    },
    onGesture(e) {
      console.log('onGesture', e)
    },
    onHistoryClick(item) {
      this.searchValue = item
      this.getWordList()
    },
    async onWordClick(word) {
      this.addHistory(word)
      this.resetData()
      this.$router.push(`/pages/dict/detail?id=${this.dictId}&word=${word}`)
    }
  },
  mounted() {
    // 初始化模块使用记录
    let dictId = JSON.parse(this.$route.query.id)
    let type

    switch (dictId) {
      case 1:
        type = MODULE_ID.DICT_YH
        break
      case 2:
        type = MODULE_ID.DICT_HY
        break
      case 3:
        type = MODULE_ID.DICT_H
        break
      case 4:
        type = MODULE_ID.DICT_GH
        break
      case 5:
        type = MODULE_ID.DICT_RY
        break
    }

    if (type) {
      this.$store.commit('setCurrentModuleUse', {
        vm: this._self,
        type,
        subjectId: ''
      })
    }

    this.init()
    this.getHistoryList()
  }
}
</script>
<style scoped lang='scss'>
.dictIndex {
  font-size: 16px;
  padding: 20px;
  background: #fff;
  border-radius: 16px;
  height: 100%;
  overflow-y: auto;

  .input-search {
    width: 100%;
    margin-bottom: 20px;

    /deep/ .el-input-group__prepend {
      background: #fff;
    }

    /deep/ .el-input__inner {
      border-radius: 8px;
      border: 1px solid #D9D9D9;

      &::placeholder {
        color: #A3A3A3;
        line-height: 44px;
      }
    }
  }

  .title {
    font-size: 20px;
    color: #333333;
    font-weight: 500;
    margin-bottom: 10px;
  }

  .list {
    display: flex;
    color: #A3A3A3;
    flex-wrap: wrap;

    .word-item {
      border-radius: 35px;
      background: #F6F6F6;
      cursor: pointer;
      height: 34px;
      line-height: 34px;
      padding: 0 20px;
      margin-right: 10px;
      margin-bottom: 10px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .word-item__more {
      @extend .word-item;
      background: #51C3FF1a;
      color: #51C3FF;

      .word-item-icon {
        font-size: 14px;
        color: #51C3FF;
        margin-left: 2px;
      }
    }
  }
}
</style>
